package control;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import business.UserManager;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession userSession = request.getSession(false);
		if(userSession==null || userSession.getAttribute("UserSession")==null)
		{
            return;
		}
		else
		{
			doPost(request,response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Get userId and password from the login form
		String userName = request.getParameter("username");
		String pasword = request.getParameter("password");
		System.out.println("user id:" +userName+ "password: " +pasword);
		if(userName==null || pasword==null || userName.equals("")|| pasword.equals("")){
			request.setAttribute("error", "Please enter your user name or password.");
			request.getRequestDispatcher("/Login.jsp").forward(request, response);
			System.out.println("user and password are null.");
		}else{
			//Validate the password and create a userSession with key userid
			UserSession userSession = null;
			try
			{
				UserManager mgr = new UserManager();
				userSession = mgr.validate(userName, pasword);
			}
			catch(Exception e)
			{
				System.out.println(e.getMessage()+ " No match data in database");
                
    			request.setAttribute("error", "Invalid user or password.");
    			request.getRequestDispatcher("/Login.jsp").forward(request, response);
    			System.out.println("Invlid user.");
    			return;
			}

           // If user is valid,create a session for the user.
          request.getSession().setAttribute("USERSESSION",userSession);
          
          RequestDispatcher rd = request.getRequestDispatcher("/CurrentBooking");
          
          if (rd != null){
              rd.forward(request,response);
          }

		}
	}

}
